package com.hjy.user.client.controller;

import com.hjy.pojo.User;
import com.hjy.service.UserService;
import com.rpc.RpcFactory;
import org.apache.zookeeper.KeeperException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    private UserService userService;
    public UserController(){
        try{
            this.userService = RpcFactory.getServiceProxy(UserService.class);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("服务："+UserService.class.getName()+" 不存在");
        }
    }

    @RequestMapping("/getUserByName")
    @ResponseBody
    public List<User> getUserByName(String name) throws NotBoundException, IOException, InterruptedException, KeeperException {
        try {
            return userService.getUsersByName(name);
        } catch (Exception e) {
            e.printStackTrace();
            //如果  服务端重启后 需要 重新获取连接 ,rmi 走的是tcp 协议
            this.userService = RpcFactory.getServiceProxy(UserService.class);
            return new ArrayList<>();
        }
    }
}
